package com.cjzuji.rental.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cjzuji.rental.Bean.ApiResponseCount;
import com.cjzuji.rental.Bean.request.tool.CreateSmsRequest;
import com.cjzuji.rental.Bean.request.tool.GetUserSmsList;
import com.cjzuji.rental.Config.AliSmsConfig;
import com.cjzuji.rental.controller.tool.ToolController;
import com.cjzuji.rental.dao.UserSmsDao;
import com.cjzuji.rental.exception.BusinessException;
import com.cjzuji.rental.pojo.UserSms;
import com.cjzuji.rental.service.ToolService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author bag
 * @version V1.0
 * @date 2025/6/12 15:54
 * @since 1.0
 */

@Service
public class ToolServiceImpl implements ToolService {

    private static final Logger log = LoggerFactory.getLogger(ToolServiceImpl.class);

    @Autowired
    private UserSmsDao userSmsDao;

    @Autowired
    private AliSmsConfig aliSmsConfig;

    // 阿里云短信初始化链接
    public static com.aliyun.dysmsapi20170525.Client createClient(AliSmsConfig aliSmsConfig) throws Exception {
        // 工程代码建议使用更安全的无AK方式，凭据配置方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.credentials.Client credential = new com.aliyun.credentials.Client();
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setCredential(credential)
                .setAccessKeyId(aliSmsConfig.getAccessKeyId())
                .setAccessKeySecret(aliSmsConfig.getAccessKeySecret());
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = aliSmsConfig.getEndpoint();
        return new com.aliyun.dysmsapi20170525.Client(config);
    }


    @Override
    public Boolean createSms(CreateSmsRequest createSmsRequest) {
        UserSms userSms = UserSms.builder()
                .username(createSmsRequest.getUsername())
                .userMobile(createSmsRequest.getUserMobile())
                .orderID(createSmsRequest.getOrderID())
                .shopName(createSmsRequest.getShopName())
                .weChat(createSmsRequest.getWeChat())
                .auditor(createSmsRequest.getAuditor())
                .smsContent(createSmsRequest.getSmsContent())
                .createTime(new Date())
                .build();
        Boolean sendSmsRes = sendSms(createSmsRequest);
        if (sendSmsRes) {
            return userSmsDao.save(userSms);
        }else {
            return false;
        }
    }

    @Override
    public ApiResponseCount<UserSms> userSmsList(GetUserSmsList getUserSmsList) {
        // 构建分页对象
        Page<UserSms> page = new Page<>(getUserSmsList.getPageIndex(), getUserSmsList.getPageSize());

        // 构建查询条件
        QueryWrapper<UserSms> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (StringUtils.hasText(getUserSmsList.getUserName())) {
            queryWrapper.like("user_name", getUserSmsList.getUserName());
        }
        if (StringUtils.hasText(getUserSmsList.getUserMobile())) {
            queryWrapper.like("user_mobile", getUserSmsList.getUserMobile());
        }
        if (StringUtils.hasText(getUserSmsList.getOrderID())) {
            queryWrapper.eq("order_id", getUserSmsList.getOrderID());
        }
        if (StringUtils.hasText(getUserSmsList.getAuditor())) {
            queryWrapper.like("auditor", getUserSmsList.getAuditor());
        }
        // 执行分页查询
        Page<UserSms> userSmsPage = userSmsDao.selectList(page,queryWrapper);
        return new ApiResponseCount<>(userSmsPage.getRecords(),(int) userSmsPage.getTotal());
    }

    public Boolean sendSms(CreateSmsRequest createSmsRequest){
        Client client = null;
        try {
            client = ToolServiceImpl.createClient(aliSmsConfig);
        }catch (Exception e){
            throw new BusinessException("-1",e.getMessage());
        }
        Map<String, String> params = new HashMap<>();
        params.put("username",createSmsRequest.getUsername());
        params.put("shopName",createSmsRequest.getShopName());
        params.put("orderID",createSmsRequest.getOrderID());
        params.put("phone",createSmsRequest.getWeChat());
        String plateParam =  JSON.toJSONString(params);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(createSmsRequest.getUserMobile())    //用户手机号手机号
                .setSignName(aliSmsConfig.getSignName())    //短信签名 名称
                .setTemplateCode(aliSmsConfig.getTemplateCode())   //短信模板code
                .setTemplateParam(plateParam);
        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, new RuntimeOptions());
            if ("OK".equals(sendSmsResponse.getBody().getCode())){
                return true;
            }else {
                throw new BusinessException("-1", sendSmsResponse.getBody().getMessage());
            }
        } catch (TeaException error) {
            throw new BusinessException("-1",error.getMessage());
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            throw new BusinessException("-1",error.getMessage());
        }
    }


}
